import { KeepAlive, ref } from 'vue'
import { defineStore } from 'pinia'
import type { RouteRecordRaw } from 'vue-router'
import router, { constantRoutes, asyncRoutes as dynamicRoutes } from '@/router'
import Layout from '@/layout/index.vue'
import ParentView from '@/components/ParentView/index.vue'
import { getUserRoutesList } from '@/apis/index.ts'
import Has from '@/utils/has'
// import { exRoutes } from './routes.ts'

// 匹配views里面所有的.vue文件
const modules = import.meta.glob('./../../views/**/*.vue')

// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRoutes: RouteRecordRaw[], lastRouter: boolean | RouteRecordRaw = false, type = false) {
  return asyncRoutes.filter((route) => {
    if (type && route.children) {
      route.children = filterChildren(route.children)
    }
    if (route.component && typeof route.component === 'string') {
      // Layout ParentView 组件特殊处理
      if (route['component'] === 'Layout') {
        route['component'] = Layout as never
      } else if (route['component'] === 'ParentView') {
        route['component'] = ParentView as never
      } else {
        route['component'] = loadView(route['component']) as never
      }
    }
    if (route.children !== null && route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children, route, type)
    } else {
      delete route['children']
      delete route['redirect']
    }
    return true
  })
}

function filterChildren(childrenRoutes: RouteRecordRaw[], lastRouter: boolean | RouteRecordRaw = false) {
  let children: RouteRecordRaw[] = []
  childrenRoutes.forEach((el, index) => {
    if (el.children && el.children.length) {
      if (typeof el.component === 'string' && el['component'] === 'ParentView' && !lastRouter) {
        ;(el['children'] as RouteRecordRaw[]).forEach((c: RouteRecordRaw) => {
          c.path = el['path'] + '/' + c.path
          if (c.children && c.children.length) {
            children = children.concat(filterChildren(c.children, c))
            return
          }
          children.push(c)
        })
        return
      }
    }
    if (lastRouter && typeof lastRouter === 'object') {
      el.path = lastRouter.path + '/' + el.path
    }
    children = children.concat(el)
  })
  return children
}

// 动态路由遍历，验证是否具备权限
export function filterDynamicRoutes(routes: RouteRecordRaw[]) {
  const arr: RouteRecordRaw[] = []
  routes.forEach((route) => {
    if (route.meta?.permissions) {
      if (Has.hasPermOr(route.meta?.permissions)) {
        arr.push(route)
      }
    } else if (route.meta?.roles) {
      if (Has.hasRoleOr(route.meta?.roles)) {
        arr.push(route)
      }
    }
  })
  return arr
}

// 加载模块
export const loadView = (view: string) => {
  let res
  for (const path in modules) {
    const dir = path.split('views/')[1].split('.vue')[0]
    if (dir === view) {
      res = () => modules[path]()
    }
  }
  return res
}

const storeSetup = () => {
  const routes = ref<RouteRecordRaw[]>([]) // 常驻路由 + 动态路由（这时候component已经从字符串转为模块）
  const topbarRoutes = ref<RouteRecordRaw[]>([]) // 页签路由
  const sidebarRoutes = ref<RouteRecordRaw[]>([]) // 侧边栏路由

  const setRoutes = (routesArray: RouteRecordRaw[]) => {
    routes.value = constantRoutes.concat(routesArray)
  }

  const setTopbarRoutes = (routes: RouteRecordRaw[]) => {
    topbarRoutes.value = routes
  }

  const setSidebarRoutes = (routes: RouteRecordRaw[]) => {
    sidebarRoutes.value = routes
  }

  // 将英文字符串第一个字母变为大写的函数
  const englishToOneBig = (str: any) => {
    let newStr = str.slice(0, 1).toUpperCase() + str.slice(1).toLowerCase()
    return newStr
  }

  // 处理数据的函数
  const disposeDataFunc = (data: any) => {
    data.splice(0, 1)
    //console.log(data,'111');
    let newData = []
    data.forEach((item: any) => {
      // 子集
      let children = []
      // 第一级自身的属性
      let obj = {}
      if (item.sunPlatFormModuleList.length == 0) {
        obj.path = ''
        obj.component = 'Layout'
        obj.redirect = item.moduleUrl
        let obj1 = {}
        obj1.path = item.moduleUrl.substr(1)
        obj1.name = englishToOneBig(obj1.path)
        // //console.log(obj1.name);
        obj1.component = obj1.path + '/index'
        let obj1_meta = {
          hidden: false,
          title: item.moduleName,
          svgIcon: 'menu-form',
          keepAlive: true
        }
        obj1.meta = obj1_meta
        children.push(obj1)
        obj.children = children
        //console.log(obj);
        newData.push(obj)
      } else {
        obj.path = item.moduleUrl
        obj.name = item.moduleUrl.substr(1)
        ;(obj.component = 'Layout'), (obj.redirect = item.moduleUrl)
        obj.meta = {
          hidden: false,
          title: item.moduleName,
          svgIcon: 'menu-form',
          keepAlive: false
        }
        obj.children = []
        item.sunPlatFormModuleList.forEach((item1) => {
          let objs = {}

          let nameRearArr = item1.moduleUrl.split('/')
          let nameRear = englishToOneBig(nameRearArr[1])
          objs.path = nameRearArr[1]
          objs.name = obj.name + nameRear
          objs.component = item1.moduleUrl
          objs.meta = {
            hidden: false,
            title: item1.moduleName,
            icon: 'icon-list',
            keepAlive: true
          }
          obj.children.push(objs)
        })
        //console.log(obj);
        newData.push(obj)
      }
    })
    return newData
  }

  /* 路由数据 */

  /** 生成路由 */
  const generateRoutes = (): Promise<RouteRecordRaw[]> => {
    //console.log('进来了');

    return new Promise((resolve) => {
      // 向后端请求路由数据
      // getUserRoutesList().then((res) => {
      // //console.log(res.data)
      // 调用处理数据的函数
      // const showData = disposeDataFunc(res.data)

      let exRoutes = [
        {
          moduleId: 1,
          moduleUrl: '/home',
          moduleName: '首页',
          moduleDesc: '',
          moduleSort: '1',
          moduleIcon: '',
          sunPlatFormModuleList: []
        },
        {
          moduleId: 2,
          moduleUrl: '/equipment',
          moduleName: '设备管理',
          moduleDesc: '',
          moduleSort: '2',
          moduleIcon: '',
          sunPlatFormModuleList: []
        },
        {
          moduleId: 3,
          moduleUrl: '/user',
          moduleName: '用户管理',
          moduleDesc: '',
          moduleSort: '3',
          moduleIcon: '',
          sunPlatFormModuleList: []
        },
        {
          moduleId: 4,
          moduleUrl: '/subUser',
          moduleName: '子用户管理',
          moduleDesc: '',
          moduleSort: '4',
          moduleIcon: '',
          sunPlatFormModuleList: []
        },
        {
          moduleId: 5,
          moduleUrl: '/equipmentType',
          moduleName: '设备型号',
          moduleDesc: '',
          moduleSort: '5',
          moduleIcon: '',
          sunPlatFormModuleList: []
        },
        {
          moduleId: 6,
          moduleUrl: '/information',
          moduleName: '数据字典',
          moduleDesc: null,
          moduleSort: '6',
          moduleIcon: '',
          sunPlatFormModuleList: []
        },
        {
          moduleId: 7,
          moduleUrl: '/authority',
          moduleName: '权限管理',
          moduleDesc: null,
          moduleSort: '7',
          moduleIcon: '',
          sunPlatFormModuleList: [
            {
              moduleId: 11,
              moduleUrl: 'authority/sysdict_items/index',
              moduleName: '角色管理',
              moduleDesc: '',
              moduleSort: '1',
              moduleIcon: ''
            },
            {
              moduleId: 12,
              moduleUrl: 'authority/parameters/index',
              moduleName: '界面配置',
              moduleDesc: '',
              moduleSort: '2',
              moduleIcon: ''
            },
            {
              moduleId: 13,
              moduleUrl: 'authority/roleAuthority/index',
              moduleName: '角色权限',
              moduleDesc: '',
              moduleSort: '3',
              moduleIcon: ''
            },
            {
              moduleId: 14,
              moduleUrl: 'authority/rolePage/index',
              moduleName: '角色界面',
              moduleDesc: '',
              moduleSort: '4',
              moduleIcon: ''
            },
            {
              moduleId: 15,
              moduleUrl: 'authority/administrator/index',
              moduleName: '管理配置',
              moduleDesc: '',
              moduleSort: '5',
              moduleIcon: ''
            }
          ]
        },
        {
          moduleId: 8,
          moduleUrl: '/files',
          moduleName: '文件管理',
          moduleDesc: '通过设备列表进入，侧边栏隐藏',
          moduleSort: '8',
          moduleIcon: '',
          sunPlatFormModuleList: []
        },
        {
          moduleId: 9,
          moduleUrl: '/personageSet',
          moduleName: '个人设置',
          moduleDesc: '通过历史数据进入，侧边栏隐藏',
          moduleSort: '9',
          moduleIcon: '',
          sunPlatFormModuleList: []
        }

        // {
        //   "moduleId": 10,
        //   "moduleUrl": "/systemSetting",
        //   "moduleName": "系统设置",
        //   "moduleDesc": "对系统进行管理设置",
        //   "moduleSort": "10",
        //   "moduleIcon": "",
        //   "sunPlatFormModuleList": []
        // }
      ]
      // let isDev = false
      // console.log(exRoutes, 'exD')
      // const exRoutesD = exRoutes
      // exRoutesD.forEach((item) => {
      //   if (item.moduleName == '设备管理') {
      //     isDev = true
      //   }
      // })
      // if (!isDev) {
      //   exRoutesD.splice(1, 0, {
      //     "moduleId": 2,
      //     "moduleUrl": "/equipment",
      //     "moduleName": "设备管理",
      //     "moduleDesc": "",
      //     "moduleSort": "2",
      //     "moduleIcon": "",
      //     "sunPlatFormModuleList": []
      //   })
      // }

      // exRoutesD.forEach((item) => {
      //   console.log('erd', item)

      // })
      // console.log(exRoutes);

      const showData = disposeDataFunc(exRoutes)
      console.log('disFuncD', showData)

      showData.push({
        name: 'https://gitee.com/lin0716/gi-demo',
        path: '/https://gitee.com/lin0716/gi-demo',
        component: 'Layout',
        meta: {
          hidden: true,
          title: '项目地址',
          svgIcon: 'menu-gitee',
          keepAlive: false
        }
      })
      console.log('disFuncD1', showData)
      //console.log(showData,'showData');

      //console.log(newData);
      const sdata = JSON.parse(JSON.stringify(showData))
      const rdata = JSON.parse(JSON.stringify(showData))
      const defaultData = JSON.parse(JSON.stringify(showData))

      const sidebarRoutes = filterAsyncRouter(sdata)
      const rewriteRoutes = filterAsyncRouter(rdata, false, true)
      const defaultRoutes = filterAsyncRouter(defaultData)

      const asyncRoutes = sidebarRoutes
      console.log(showData, 'showD')

      asyncRoutes.forEach((route) => {
        router.addRoute(route)
      })

      setRoutes(rewriteRoutes)
      // //console.log('常驻路由constantRoutes', constantRoutes)
      setSidebarRoutes(constantRoutes.concat(sidebarRoutes))
      setTopbarRoutes(defaultRoutes)
      resolve(rewriteRoutes)
    })
    // })
  }

  return {
    routes,
    topbarRoutes,
    sidebarRoutes,
    generateRoutes
  }
}

export const usePermissionStore = defineStore('permission', storeSetup, { persist: true })
